// user的 处理函数

// 导入数据库
const db = require("../db/index");

const express = require("express");
// 配置跨域

// 生成随机数
const createNumber = require("../utils/randomNumber");

const cors = require("cors");
const app = express();

const http = require("http");
const socketIO = require("socket.io");
const { combineTableNames } = require("sequelize/lib/utils");
const server = http.createServer(app);
const io = socketIO(server, {
  cors: {
    origin: "*", // 允许所有源
    methods: ["GET", "POST"], // 允许的 HTTP 方法
  },
});

/**
 *   room_id: data.roomId,
        username: data.username,
        message: data.message,
        avatar: data.avatar,
 
 */
// exports.chat = (req, res) => {
//   io.on("connection", (socket) => {
//     socket.on("joinRoom", (roomId) => {
//       socket.join(roomId);
//     });
//     //离开房间
//     socket.on("leaveRoom", (roomId) => {
//       socket.leave(roomId);
//     });
//     //聊天消息
//     socket.on("chatMessage", (data) => {
//       //创建消息对象
//       const messageInfo = {
//         user_id: data.user_id,
//         room_id: data.room_id,
//         username: data.username,
//         message: data.message,
//         avatar: data.avatar,
//         moment: new Date(),
//       };

//       const sql = `insert into message set ?`;
//       //存入数据库
//       db.query(sql, messageInfo, (err, results) => {
//         if (err) return err;
//         // 存入成功后广播消息到指定房间中，除了发送者之外的其他成员
//         socket.broadcast.to(data.room_id).emit("chatMessage", messageInfo);
//         res.cc("存入成功", 0);
//       });
//     });
//   });
// };

/**
 *
 * @param {获取默认群聊} req
 * @param {*} res
 */
exports.getDefaultRoom = (req, res) => {
  const sql = `select * from room where type = 1`;
  db.query(sql, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      message: "获取成功",
      status: 0,
      data: results,
    });
  });
};

/**
 *  query user_id room_id
 * @param {群主踢人} req
 * @param {*} res
 */
exports.deleteUser = (req, res) => {
  //  TOdo：删除
 
  const sql = `update user_room set is_delete = 1 where user_id = ? and  room_id = ? `;
  db.query(sql, [req.query.user_id, req.query.room_id], (err, results) => {
    if (err) return res.cc(err);
    res.cc("删除成功", 0);
  });
};

/**
 * params 获取当前所在群聊所有用户
 * @param {room_id} req
 * @param {*} res
 */
exports.getRoomUsers = (req, res) => {
  const sql = `select user_room.*,users.username from user_room,users where user_room.room_id = ? and user_room.user_id = users.id  and user_room.user_id != ? and  is_delete!=1 and isInRoom = 1`;
  db.query(sql, [req.query.room_id, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      message: "获取群聊用户信息成功",
      status: 0,
      data: results,
    });
  });
};

/**
 *
 * @param {获取当前所在房间} req
 * @param {*} res
 */
exports.getCurrentRoom = (req, res) => {
  const sql = `select * from user_room where user_id = ? and is_delete!=1 and isInRoom = 1`;
  db.query(sql, [req.user.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.length === 0) {
      res.cc("为查找到房间", 0);
    } else {
      res.send({
        status: 0,
        message: "获取当前所在房间成功",
        data: results,
      });
    }
  });
};
/**
 * params page pageSize
 * @param {room_id} req 获取房间的聊天记录
 * @param {*} res
 */

exports.getMessage = (req, res) => {
  const sql = `select * from message where room_id = ? order by moment desc limit ? offset ?`;
 
  const page = parseInt(req.query.page);
  const pageSize = parseInt(req.query.pageSize);
  const offset = (page - 1) * pageSize;
  db.query(sql, [req.query.room_id, pageSize, offset], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "获取群聊聊天信息成功",
      data: results,
    });
  });
};

/**
 *
 * @param {获取我创建的房间} req
 * @param {id type user_id number name avatar moment info } res
 */
exports.getMyCreateRooms = (req, res) => {
  const sql = `select * from room where user_id = ? and is_delete !=1`;
  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "获取成功",
      data: results,
    });
  });
};

/**
 *params text
 * @param {模糊查询群聊} req
 *  code 0 为按number  1 为按群名
 * @param {*} res
 */
exports.searchRoom = (req, res) => {
  // 按名称
  const sql = `select * from room where name like ?  and is_delete != 1 and  user_id != ? and user_id  is not null`;
  // 按群号
  const sql2 = `select * from room where number = ? and is_delete != 1 and  user_id != ? and user_id is not null `;

  const serch = `%${req.query.number}%`;
  if (req.query.code == 1) {
    db.query(sql, [serch, req.user.id], (err, results) => {
      if (err) return res.cc(err);
      res.send({
        status: 0,
        message: "搜索成功",
        data: results,
      });
    });
  } else {
    db.query(sql2, [req.query.number, req.user.id], (err, results) => {
      if (err) return res.cc(err);
      res.send({
        status: 0,
        message: "搜索成功",
        data: results,
      });
    });
  }
};

/**
 *
 * @param {获取所有房间信息 id name avatar moment } req
 * @param {*} res
 */
exports.getAllRooms = (req, res) => {
  const sql = `select * from room where is_delete !=1`;
  db.query(sql, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      data: results,
    });
  });
};
/**
//  *  query----type -- 0
//  * @param {获取我的所有房间---type 0 为我加入的 1 为我创建的} req
//  * @param {*} res
//  */
// exports.getMyRooms = (req, res) => {
//   const sql = `select user_room.*,room.number,room.author_name,room.moment as create_moment,room.info from user_room , room where user_room.user_id = ? and user_room.is_delete !=1 and room.id = user_room.room_id and user_room.author_id != ? `;
//   db.query(sql, [req.user.id, req.user.id], (err, results) => {
//     if (err) return res.cc(err);
//     res.send({
//       status: 0,
//       messaeg: "获取成功",
//       data: results,
//     });
//   });
// };

// exports.getMyRooms = (req,res)=>{
//   const sql = `select * from room where user_id = `

// }
exports.getMyRooms = (req, res) => {
  const sql = `
    SELECT user_room.*, room.number, room.author_name, room.moment AS create_moment, room.info 
    FROM (
      SELECT user_room.*, ROW_NUMBER() OVER(PARTITION BY user_room.room_id ORDER BY user_room.id) AS rn
      FROM user_room
      WHERE user_room.user_id = ? AND user_room.is_delete != 1 AND user_room.author_id != ?
    ) AS user_room
    JOIN room ON user_room.room_id = room.id
    WHERE user_room.rn = 1
  `;
  db.query(sql, [req.user.id, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "获取成功",
      data: results,
    });
  });
};

/** body创建房间
 *创建时 加两个，一个是room 一个是user_room
 * @param { number 房间号 name 房间名,avatar 房间头像 info 房间信息,author_name 群主名} req
 * @param {*} res
 */
exports.createRoom = (req, res) => {
  const sql = `insert into room set ?`;
  const sql3 = `select id from room where name = ? `;
  const sql2 = `insert into user_room set ?`;
  const sql4 = `select user_pic from users where id = ?`;
  const createInfo = {
    ...req.body,
    user_id: req.user.id,
    moment: new Date(),
    number: createNumber(),
  };
  db.query(sql, createInfo, (err, results) => {
    if (err) return res.cc(err);
    db.query(sql3, createInfo.name, (err, result) => {
      if (err) return res.cc(err);
      db.query(sql4, req.user.id, (err, result3) => {
        if (err) return res.cc(err);
        const user_roomInfo = {
          user_id: createInfo.user_id,
          created_at: createInfo.moment,
          type: 1,
          name: createInfo.name,
          avatar: req.body.avatar,
          user_pic: result3[0].user_pic,
          room_id: result[0].id,
        };
        db.query(sql2, user_roomInfo, (err, result2) => {
          if (err) return res.cc(err);
          res.send({
            status: 0,
            message: "创建成功",
          });
        });
      });
    });
  });
};

/** body 加入房间
 *后传 user_id 加入房间 更新房间isInroom为 0 再加 房间名
 * @param {room_id,avatar,name ,author_id} req
 * @param {*} res
 */
exports.joinRoom = (req, res) => {
  const sql = `insert into user_room  set ? `;
  const sql4 = `select user_pic from users where id = ?`;
  db.query(sql4, [req.user.id], (err, results) => {
    if (err) return res.cc(err);
 
    const joinInfo = {
      ...req.body,
      user_id: req.user.id,
      moment: new Date(),
      isInRoom: 1,
      type: 0,
      user_pic: results[0].user_pic,
    };
    db.query(sql, joinInfo, (err, result) => {
 
      if (err) return res.cc(err);
      res.send({
        status: 0,
        message: "加入成功",
      });
    });
  });
};

/**
 *room_id
 * @param {更新该用户目前所在房间状态全为0} req
 * @param {*} res
 */
exports.updateRoomIsInRoom = (req, res) => {
  const sql = `update user_room set isInRoom = 0 where user_id = ? `;
  db.query(sql, [req.user.id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "更新状态成功",
    });
  });
};

/** query
 * 切换房间 切换当前房间信息 --将isInRoom换为 1 表示目前在这个房间
 * @param {room_id} req
 * @param {*} res 返回current_roomInfo返回当前房间的信息
 */
exports.checkRoom = (req, res) => {
  const sql = `update user_room set isInRoom = 1 where room_id = ? and user_id = ?`;
  const sql2 = `slect * from room where id = ?`;
  db.query(sql, [req.query.room_id, req.user.id], (err, results) => {
    db.query(sql2, [req.query.id], (err, result) => {
      if (err) return res.cc(err);
      res.send({
        status: 0,
        message: "获取成功",
        data: result,
      });
    });
  });
};

/**
 *退出群聊 query
 * @param {退出群聊 room_id} req
 * @param {*} resj
 */
exports.leaveMyRoom = (req, res) => {
  const sql = `update user_room set isInRoom = 0 ,is_delete = 1 where room_id  = ? and user_id  = ?`;
  db.query(sql, [req.query.room_id, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    res.cc("删除成功", 0);
  });
};

/**
 *解散群聊 query
 * @param {room_id} req
 * @param {*} res
 */
exports.deleteRoom = (req, res) => {
  const sql = `update room set is_delete = 1 where id = ? `;
  const sql2 = `update user_room set isInRoom = 0,is_delete = 1 where room_id = ? `;
  const sql3 = `update message set is_delete = 1 where room_id = ?`;
  db.query(sql, [req.query.room_id], (err, results) => {
    if (err) return res.cc(err);
 
 
    db.query(sql2, [req.query.room_id], (err, result2) => {
      if (err) return res.cc(err);
 
      db.query(sql3, [req.query.room_id], (err, result3) => {
      
        res.cc("解散成功", 0);
      });
    });
  });
};
